package util;

import java.awt.Component;
import java.awt.FontMetrics;

public class CommUtils {

	public static String getMaxWidthString(String str, Component comp, int maxWidth) {
		FontMetrics fm = comp.getFontMetrics(comp.getFont());
		return getMaxWidthString(str, fm, maxWidth);
	}
    
	public static String getMaxWidthString(String str, FontMetrics fm, int maxWidth) {
		if(fm == null)
			return str;
    	
		String lastStr = "...";
		if (fm.stringWidth(str) > maxWidth) {
			for (int i = 0; i < str.length(); i++) {
				String subString = str.substring(0, i) + "...";
				if (fm.stringWidth(subString) > maxWidth) {
					return lastStr;
				}
				lastStr = subString;
			}
		}
		return str;
	}
}
